package com.sxpi.zixun.valid;

import com.sxpi.zixun.valid.annotation.ValidEmail;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: 董伟豪
 * @Date: 2022/8/25 13:31
 * 校验注解实现
 */
public class EmailValidator implements ConstraintValidator<ValidEmail, String> {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    @Override
    public void initialize(final ValidEmail constraintAnnotation) {}

    /**
     * 如果是 true 就通过， false代表不合法，之间报错message
     * @param email
     * @param context
     * @return
     */
    @Override
    public boolean isValid(final String email, final ConstraintValidatorContext context) {
        if(StringUtils.isEmpty(email)){
            return true;
        }
        return validateEmail(email);
    }

    private boolean validateEmail(final String email) {
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
